<template>
	<div>
		<el-breadcrumb separator-class="el-icon-arrow-right">
			<el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
			<el-breadcrumb-item>商品管理</el-breadcrumb-item>
			<el-breadcrumb-item>参数列表</el-breadcrumb-item>
		</el-breadcrumb>
		<el-card>
			<el-alert title="注意:只允许为第三级分类设置相关参数!" type="warning" :closable="false" show-icon>
			</el-alert>
			<!-- 选择商品分类区域 -->
			<el-row>
				<el-col>
					<span>选择商品分类：</span>
					<el-cascader v-model="selectedKeys" :options="cateList" expandTrigger="hover" :props="cascadershu"
						@change="handleChange" clearable></el-cascader>
				</el-col>
			</el-row>
			<!-- 标签页 -->
			<el-tabs v-model="activeName" @tab-click="handleTabClick">
				<el-tab-pane label="动态参数" name="many">
					<el-row>
						<el-col>
							<el-button type="primary" size="mini" @click="addManyButton" :disabled="isBtnDisabled">添加参数
							</el-button>
						</el-col>
					</el-row>
					<el-table :data="manyTableData" border stripe>
						<!-- 展开行 -->
						<el-table-column type="expand">
							<template slot-scope="scope">
								<el-tag @close="handleClose(i,scope.row)" v-for="(item,i) in scope.row.attr_vals"
									:key="i" closable>{{item}}</el-tag>
								<el-input style="width: 100px;" v-if="scope.row.inputVisible"
									v-model="scope.row.inputValue" ref="saveTagInput" size="small"
									@keyup.enter.native="handleInputConfirm(scope.row)"
									@blur="handleInputConfirm(scope.row)">
								</el-input>
								<el-button v-else class="button-new-tag" size="small" @click="showTagInput(scope.row)">+
									New Tag</el-button>
							</template>
						</el-table-column>
						<el-table-column type="index" label="#"></el-table-column>
						<el-table-column prop="attr_name" label="参数名称"></el-table-column>
						<el-table-column label="操作">
							<template slot-scope="scope">
								<el-button type="primary" size="small" icon="el-icon-edit"
									@click="showEditDialog(scope.row.attr_id)">编辑</el-button>
								<el-button type="danger" size="small" icon="el-icon-delete"
									@click="removeParams(scope.row.attr_id)">删除</el-button>
							</template>
						</el-table-column>
					</el-table>
				</el-tab-pane>
				<el-tab-pane label="静态属性" name="only">
					<el-row>
						<el-col>
							<el-button type="primary" @click="addManyButton" :disabled="isBtnDisabled" size="mini">添加属性
							</el-button>
						</el-col>
					</el-row>
					<el-table :data="onlyTableData" border stripe>
						<el-table-column type="expand">

							<template slot-scope="scope">
								<el-tag @close="handleClose(i,scope.row)" v-for="(item,i) in scope.row.attr_vals"
									:key="i" closable>{{item}}</el-tag>
								<el-input style="width: 100px;" v-if="scope.row.inputVisible"
									v-model="scope.row.inputValue" ref="saveTagInput" size="small"
									@keyup.enter.native="handleInputConfirm(scope.row)"
									@blur="handleInputConfirm(scope.row)">
								</el-input>
								<el-button v-else class="button-new-tag" size="small" @click="showTagInput(scope.row)">+
									New Tag</el-button>
							</template>
						</el-table-column>
						<el-table-column type="index" label="#"></el-table-column>
						<el-table-column prop="attr_name" label="属性名称"></el-table-column>
						<el-table-column label="操作">
							<template slot-scope="scope">
								<el-button type="primary" size="small" icon="el-icon-edit"
									@click="showEditDialog(scope.row.attr_id)">编辑</el-button>
								<el-button type="danger" size="small" icon="el-icon-delete"
									@click="removeParams(scope.row.attr_id)">删除</el-button>
							</template>
						</el-table-column>
					</el-table>
				</el-tab-pane>
			</el-tabs>
		</el-card>
		<!-- 添加动态参数或静态属性弹框 -->
		<el-dialog @close="manyDialogClosed" :title="'添加'+titleText" :visible.sync="manyDialogVisible" width="50%">
			<el-form :model="manyFormList" :rules="manyFormRules" ref="manyFormRef">
				<el-form-item :label="titleText" label-width="100px" prop="attr_name">
					<el-input v-model="manyFormList.attr_name"></el-input>
				</el-form-item>
			</el-form>
			<span slot="footer" class="dialog-footer">
				<el-button @click="manyDialogVisible = false">取 消</el-button>
				<el-button type="primary" @click="manyDialogPost">确 定</el-button>
			</span>
		</el-dialog>
		<!-- 修改参数的对话框 -->
		<el-dialog @close="editDialogClosed" :title="'修改'+titleText" :visible.sync="editDialogVisible" width="50%">
			<el-form :model="editFormList" :rules="manyFormRules" ref="editFormRef">
				<el-form-item :label="titleText" label-width="100px" prop="attr_name">
					<el-input v-model="editFormList.attr_name"></el-input>
				</el-form-item>
			</el-form>
			<span slot="footer" class="dialog-footer">
				<el-button @click="editDialogVisible = false">取 消</el-button>
				<el-button type="primary" @click="editDialogPost">确 定</el-button>
			</span>
		</el-dialog>
	</div>
</template>

<script>
	export default {
		data() {
			return {
				//指定默认选中的页签
				activeName: 'many',
				// 级联选择框双向绑定的数组
				selectedKeys: [],
				//级联选择框的数据
				cateList: [],
				//级联选择框的配置对象
				cascadershu: {
					label: 'cat_name',
					value: 'cat_id',
					children: 'children'
				},
				//修改对话框绑定数据
				editFormList: {
					attr_name: ''
				},
				//动态表格数据
				manyTableData: [],
				//静态表格数据
				onlyTableData: [],
				//动态参数弹框
				manyDialogVisible: false,
				//修改弹框
				editDialogVisible: false,
				manyFormList: {
					attr_name: ''
				},
				manyFormRules: {
					attr_name: [{
						required: true,
						message: '请输入',
						trigger: 'blur'
					}, ]
				},
				property: 0
			}
		},
		created() {
			this.getCateList()
		},
		methods: {
			//删除Tag
			handleClose(tagID, row) {
				row.attr_vals.splice(tagID, 1)
				this.addTag(row)
			},
			async addTag(row) {
				const {
					data: res
				} = await this.$http.put(`categories/${this.cateId}/attributes/${row.attr_id}`, {
					attr_name: row.attr_name,
					attr_sel: row.attr_sel,
					attr_vals: row.attr_vals.join(' ')
				})
				if (res.meta.status !== 200) return this.$message.error(res.meta.msg)
				this.$message.success(res.meta.msg)
			},
			// 添加Tag事件
			handleInputConfirm(row) {
				if (row.inputValue.trim().length === 0) {
					row.inputValue = ''
				} else {
					row.attr_vals.push(row.inputValue.trim())
					row.inputValue = ''
					this.addTag(row)
				}
				row.inputVisible = false
			},
			//控制添加Tag
			showTagInput(row) {
				row.inputVisible = true
				//让文本框自动获得焦点
				// $nextTick当页面上的元素重新渲染之后，才会运行回调函数中的代码
				this.$nextTick(_ => {
					this.$refs.saveTagInput.$refs.input.focus();
				});
			},
			//删除属性
			removeParams(attrId) {
				this.$confirm('此操作将永久删除该属性, 是否继续?', '提示', {
					confirmButtonText: '确定',
					cancelButtonText: '取消',
					type: 'warning'
				}).then(async () => {
					const {
						data: res
					} = await this.$http.delete(`categories/${this.cateId}/attributes/${attrId}`)
					if (res.meta.status !== 200) return this.$message.error(res.meta.msg)
					this.$message({
						type: 'success',
						message: '删除成功!'
					});
					this.getParamsData()
				}).catch(() => {
					this.$message({
						type: 'info',
						message: '已取消删除'
					});
				});
			},
			editDialogPost() {
				this.$refs.editFormRef.validate(async vali => {
					if (!vali) return
					const {
						data: res
					} = await this.$http.put(`categories/${this.cateId}/attributes/${this.property}`, {
						attr_name: this.editFormList.attr_name,
						attr_sel: this.activeName
					})
					if (res.meta.status !== 200) return this.$message.error(res.meta.msg)
					this.$message.success(res.meta.msg)
					this.getParamsData()
					this.editDialogVisible = false
				})

			},
			//重置表单
			manyDialogClosed() {
				this.$refs.manyFormRef.resetFields()
			},
			//重置表单
			editDialogClosed() {
				this.$refs.editFormRef.resetFields()
			},
			//编辑按钮
			async showEditDialog(rowId) {
				this.property = rowId
				const {
					data: res
				} = await this.$http.get(`categories/${this.cateId}/attributes/${rowId}`, {
					params: {
						attr_sel: this.activeName
					}
				})
				if (res.meta.status !== 200) return this.$message.error(res.meta.msg)
				this.editFormList = res.data
				this.editDialogVisible = true

			},
			//添加动态参数确认事件
			manyDialogPost() {
				this.$refs.manyFormRef.validate(async msg => {
					if (!msg) return this.$message.error('表单输入错误！')
					const {
						data: res
					} = await this.$http.post(`categories/${this.selectedKeys[2]}/attributes`, {
						attr_name: this.manyFormList.attr_name,
						attr_sel: this.activeName
					})
					if (res.meta.status !== 201) return this.$message.error(res.meta.msg)
					this.$message.success(res.meta.msg)
					this.getParamsData()
					this.manyDialogVisible = false
				})
			},
			// 添加动态参数按钮事件
			addManyButton() {
				this.manyDialogVisible = true
			},
			//添加静态属性按钮事件
			addOnlyButton() {
				this.onlyDialogVisible = true
			},
			// 标签页切换事件
			handleTabClick() {
				this.getParamsData()
			},
			//级联选择框数据改变事件
			handleChange() {
				this.getParamsData()
			},
			//获取参数列表
			async getParamsData() {
				if (this.cateId !== null) {
					const {
						data: res
					} = await this.$http.get(`categories/${this.cateId}/attributes`, {
						params: {
							sel: this.activeName
						}
					})
					if (res.meta.status !== 200) {
						return this.$message.error(res.meta.msg)
					}
					res.data.forEach(item => {
						item.attr_vals = item.attr_vals ? item.attr_vals.split(' ') : []
						item.inputVisible = false
						item.inputValue = ''
					})
					if (this.activeName === 'many') {
						this.manyTableData = res.data
						return
					}
					this.onlyTableData = res.data
				}
			},
			//获取级联选择框的数据
			async getCateList() {
				const {
					data: res
				} = await this.$http.get('categories')
				if (res.meta.status !== 200) return this.$message.error(res.meta.msg)
				this.cateList = res.data
			}
		},
		computed: {
			isBtnDisabled() {
				if (this.selectedKeys.length != 3) {
					return true
				}
				return false
			},
			cateId() {
				if (this.selectedKeys.length === 3) {
					return this.selectedKeys[2]
				}
				return null
			},
			titleText() {
				if (this.activeName === 'many') {
					return '动态参数'
				} else {
					return '静态属性'
				}
			}
		}
	}
</script>

<style scoped="scoped">
	.el-alert {
		margin-bottom: 20px;
	}

	.el-tag {
		margin-right: 15px;
	}
</style>
